from ctypes import CDLL,byref,create_string_buffer
from ctypes import cdll
from genericpath import exists
import json
import base64
import time
import os
import os.path as osp
import shutil
import io
from collections import defaultdict
from numpy.lib.npyio import save
from tqdm import tqdm
from PIL import Image
import numpy as np
import sys
import cv2
import requests
from hashlib import md5
import hashlib
import re
import pyautogui
 

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return obj.decode("utf-8")
        else:
            return super(MyEncoder, self).default(obj)

# 递归获取文件夹下所有符合条件的文件路径.
def get_all_filepath(root_dir_path, extension_tag=[], recursive = True):
    """
    Args:
        root_dir_path: 文件根目录.
        extension_tag: 文件后缀名组成的列表, Example: ["jpg", "png", "bmp"]
        如果为空 则获取所有
    Returns:
        特定文件夹下所有符合条件的文件路径.
    """
    def check_endswith(new_path, extension_tag):
        if len(extension_tag) == 0:
            return True
        for s in extension_tag:
            if new_path.lower().endswith(s):
                return True
        return False

    paths = []
    for f in os.listdir(root_dir_path):
        new_path = root_dir_path + os.sep + f
        if os.path.isfile(new_path) and check_endswith(new_path,  extension_tag):
            paths.append(new_path)
        elif os.path.isdir(new_path) and recursive:
            temp_list = get_all_filepath(new_path, extension_tag)
            paths.extend(temp_list)
    return paths

# 递归获取文件夹下所有最后一层子文件夹.
def get_last_dir(root_dir_path, recursive = True):
    """
    Args:
        root_dir_path: 文件夹根目录.
    Returns:
        特定文件夹下所有的文件夹路径.
    """
    paths = []
    for f in os.listdir(root_dir_path):
        new_path = root_dir_path + os.sep + f
        if osp.isdir(new_path):
            ps = get_last_dir(new_path, recursive)
            paths.extend(ps)
    if len(paths) == 0:
        paths.append(root_dir_path)
    return paths

def win_screenshot(save_dir, img_cnt):
    img = pyautogui.screenshot(region=[322,1006,400,21]) # x,y,w,h  
    sub_dir = osp.join(save_dir, str(img_cnt // 1000))
    os.makedirs(sub_dir, exist_ok=True)

    img.save(osp.join(sub_dir, "{}.jpg".format(img_cnt)))
    img = np.asarray(img)

    buffer = io.BytesIO()
    rgb_img = img[:, : , ::-1]
    pil_image = Image.fromarray(rgb_img) 
    pil_image.save(buffer, format="jpeg")
    encoded = base64.b64encode(buffer.getvalue())
    return encoded

def rec_text(save_dir, img_cnt):
    encoded = win_screenshot(save_dir, img_cnt)
    rec_data = post_rec(encoded)
    if rec_data is None or rec_data["code"] != 0: return None, None, None
    text = rec_data["items"][0]["text"]

    reg = re.compile(r"(\d+.\d+).*?(\d+.\d+).*?(\d+.\d+)")
    outs = reg.findall(text)
    if len(outs) != 1 or len(outs[0]) != 3: return None, None, None
    print(outs[0][0], outs[0][1], outs[0][2])
    return outs[0][0], outs[0][1], outs[0][2]


def rec_to_text(save_dir, easts, norths):
    time.sleep(5)
    screen_min_x = 523
    screen_max_x = 1591
    screen_min_y = 162
    screen_max_y = 988

    write_data = open(osp.join(save_dir, "data.list"), "w")

    minx = screen_min_x
    maxx = screen_max_x
    miny = screen_min_y
    maxy = screen_max_y
    img_cnt = 0
    for y in range(miny, maxy):

        for x in range(minx, maxx):
            if img_cnt < 1062: 
                img_cnt += 1
                continue

            pyautogui.moveTo(x, y, duration=0.1)
            e, n , h = rec_text(save_dir, img_cnt)
            write_data.write("{} {} {} {}\n".format(img_cnt, e, n ,h))

            img_cnt += 1

    write_data.close()


def post_rec(img_b64):
    data = { 
        "img_b64": img_b64,
        "mdl_idx": 1,                       # 1                     # 3                 # 1
        "algo_type": "TextRec",         # VihicleDetection      # SlopeDetection    # FireWarning
        "mdl_type": "text_rec"
    }
    url = "http://192.168.10.167:9998/api/rec"
    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    string = json.dumps(data, cls=MyEncoder)
    r = requests.post(url, data=string, headers=headers)
    rec_data = r.json()
    if rec_data["code"] != 0: 
        print(rec_data)
        return None
    return rec_data


if __name__ == "__main__":
    """
    东经108.155744北纬26.503612°高程849.59米
    东经108.186585°北纬26.487838°高程910.17米
    """
    save_dir = r"F:\work\code\data\height"
    east = [108.155744, 108.186585]
    north = [26.503612, 26.487838]
    rec_to_text(save_dir, east, north)
    
    # win_screenshot()